package com.jshongli.myapplication.common.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.util.Base64;
import android.util.TypedValue;
import android.view.View;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by Administrator on 2017/8/16.
 */

public class BitmapUtils {

    /**
     * 绘制图片，底部是text的效果
     **/
    public static Bitmap GetImageWithText(Context context, int resId, String label) {

        final float scale = context.getResources().getDisplayMetrics().density;

        Bitmap photo = BitmapFactory.decodeResource(context.getResources(), resId);
        int lenth = label.length();
        int width = (int) (lenth <= 6 ? 200 : (lenth * 10 * scale + 0.5f));

        Bitmap bitmap = Bitmap.createBitmap(width, 120, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint photoPaint = new Paint(Paint.ANTI_ALIAS_FLAG);// 抗锯齿
        // 获取更清晰的图像采样，防抖动
        photoPaint.setDither(true);
        // 过滤一下，抗剧齿
        photoPaint.setFilterBitmap(true);

        Rect src = new Rect(0, 0, photo.getWidth(), photo.getHeight());// 创建一个指定的新矩形的坐标
        Rect dst = new Rect(width / 2 - 30, 30, width / 2 + 30, 90);// 创建一个指定的新矩形的坐标
        canvas.drawBitmap(photo, src, dst, photoPaint);

        Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setColor(Color.BLACK);
        // sp----->px单位变换
        int sp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10, // 多少sp
                context.getResources().getDisplayMetrics());// 屏幕的密度
        textPaint.setTextSize(sp);
        // 获得输入字的宽高
        Rect bounds = new Rect();
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.getTextBounds(label, 0, label.length(), bounds);
        canvas.drawText(label, (float) width / 2, 118.0f, textPaint);
        return bitmap;
    }


    /**
     * 数字编号
     **/
    public static Bitmap GetImageByNum(Context context, String num, int color) {
        Bitmap bitmap = Bitmap.createBitmap(80, 80, Bitmap.Config.ARGB_8888);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);// 抗锯齿
        Canvas canvas = new Canvas(bitmap);
//        int activity_play= (int)(Math.random()*6);
//        paint.setColor(Color.parseColor(Contact.ImageBgColor[activity_play]));
        paint.setColor(ContextCompat.getColor(context, color));
        paint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(40, 40, 40, paint);
        paint.setColor(Color.WHITE);
        int sp = 0;
        String text = num;
        // sp----->px单位变换
        if (num.length() > 2) {
            sp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10, // 多少sp
                    context.getResources().getDisplayMetrics());// 屏幕的密度
        } else {
            sp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 13, // 多少sp
                    context.getResources().getDisplayMetrics());// 屏幕的密度
        }

        paint.setTextSize(sp);
        // 获得输入字的宽高
        Rect bounds = new Rect();
        paint.setTextAlign(Paint.Align.CENTER);
        paint.getTextBounds(text, 0, text.length(), bounds);
        Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
        float baseline = (80.0f - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
        canvas.drawText(text, 40.0f, baseline, paint);
        return bitmap;
    }

    public static Bitmap GetImageByNum2(Context context, String num, int color) {
        Bitmap bitmap = Bitmap.createBitmap(80, 80, Bitmap.Config.ARGB_8888);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);// 抗锯齿
        Canvas canvas = new Canvas(bitmap);
//        int activity_play= (int)(Math.random()*6);
//        paint.setColor(Color.parseColor(Contact.ImageBgColor[activity_play]));
        paint.setColor(ContextCompat.getColor(context, color));
        paint.setStyle(Paint.Style.STROKE);
        canvas.drawCircle(40, 40, 40, paint);
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.BLACK);
        int sp = 0;
        String text = num;
        // sp----->px单位变换
        if (num.length() > 2) {
            sp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10, // 多少sp
                    context.getResources().getDisplayMetrics());// 屏幕的密度
        } else {
            sp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 13, // 多少sp
                    context.getResources().getDisplayMetrics());// 屏幕的密度
        }

        paint.setTextSize(sp);
        // 获得输入字的宽高
        Rect bounds = new Rect();
        paint.setTextAlign(Paint.Align.CENTER);
        paint.getTextBounds(text, 0, text.length(), bounds);
        Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
        float baseline = (80.0f - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
        canvas.drawText(text, 40.0f, baseline, paint);
        return bitmap;
    }

    /**
     * 这里是对头像进行动态绘制的
     **/
    public static Bitmap GetUserImageByNickName(Context context, String nickname, int color) {
        Bitmap bitmap = Bitmap.createBitmap(80, 80, Bitmap.Config.ARGB_8888);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);// 抗锯齿
        Canvas canvas = new Canvas(bitmap);
//        int activity_play= (int)(Math.random()*6);
//        paint.setColor(Color.parseColor(Contact.ImageBgColor[activity_play]));
        paint.setColor(context.getResources().getColor(color));
        paint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(40, 40, 40, paint);
        paint.setColor(Color.WHITE);
        // sp----->px单位变换
        int sp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 13, // 多少sp
                context.getResources().getDisplayMetrics());// 屏幕的密度
        paint.setTextSize(sp);
        // 获得输入字的宽高
        Rect bounds = new Rect();
        String text = getNewText(nickname);
        paint.setTextAlign(Paint.Align.CENTER);
        paint.getTextBounds(text, 0, text.length(), bounds);
        Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
        float baseline = (80.0f - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
        canvas.drawText(text, 40.0f, baseline, paint);
        return bitmap;
    }


    public static Bitmap GetRectUserImage(Context context, String nickname, int color) {
        Bitmap bitmap = Bitmap.createBitmap(120, 120, Bitmap.Config.ARGB_8888);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);// 抗锯齿
        Canvas canvas = new Canvas(bitmap);

        // 新建一个矩形
        RectF outerRect = new RectF(0, 0, 120, 120);
//        int activity_play= (int)(Math.random()*6);
//        paint.setColor(Color.parseColor(Contact.ImageBgColor[activity_play]));
        paint.setColor(context.getResources().getColor(color));
        paint.setStyle(Paint.Style.FILL);
        canvas.drawRoundRect(outerRect, 20, 20, paint);
        paint.setColor(Color.WHITE);
        // sp----->px单位变换
        int sp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 15, // 多少sp
                context.getResources().getDisplayMetrics());// 屏幕的密度
        paint.setTextSize(sp);
        // 获得输入字的宽高
        Rect bounds = new Rect();
        String text = getNewText(nickname);
        paint.setTextAlign(Paint.Align.CENTER);
        paint.getTextBounds(text, 0, text.length(), bounds);
        Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
        float baseline = (120.0f - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
        canvas.drawText(text, 60.0f, baseline, paint);
        return bitmap;
    }


    /**
     * 返回处理过的昵称，保证显示1个或1个一下
     */
    private static String getNewText(String content) {
        String text;
        if (content.length() > 1) {
            text = content.substring(0, 1);
        } else {
            text = content;
        }
        return text;
    }

    // 判断一个字符是否是中文
    public static boolean isChinese(char c) {
        return c >= 0x4E00 && c <= 0x9FA5;// 根据字节码判断
    }

    // 判断一个字符串是否含有中文
    public static boolean isChinese(String str) {
        if (str == null) return false;
        for (char c : str.toCharArray()) {
            if (isChinese(c)) return true;// 有一个中文字符就返回
        }
        return false;
    }


    // 将bitmap转成string类型通过Base64
    public static String BitmapToString(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //可以设计添加头
        //String title=""data:image/jpeg;base64,";
        //return title+result;

        return result;

    }

    /**
     * * base64转为bitmap
     * * @param base64Data
     * * @return
     */
    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data.replaceFirst("data:image/jpeg;base64,", "").trim(), Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    public static Bitmap base64ToBitmap2(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    /**
     * 获取视频文件截图
     *
     * @param path 视频文件的路径
     * @return Bitmap 返回获取的Bitmap
     */

    public static Bitmap getVideoThumb(String path) {

        MediaMetadataRetriever media = new MediaMetadataRetriever();

        media.setDataSource(path);

        return media.getFrameAtTime();

    }

    /**
     * 获取视频文件缩略图 API>=8(2.2)
     *
     * @param path 视频文件的路径
     * @param kind 缩略图的分辨率：MINI_KIND、MICRO_KIND、FULL_SCREEN_KIND
     * @return Bitmap 返回获取的Bitmap
     */

    public static Bitmap getVideoThumb2(String path, int kind) {

        return ThumbnailUtils.createVideoThumbnail(path, kind);

    }

    public static Bitmap getVideoThumb2(String path) {

        return getVideoThumb2(path, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);

    }

    /**
     * 把布局变成Bitmap
     *
     * @param addViewContent
     * @return
     */
    public static Bitmap getViewBitmap(View addViewContent) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            addViewContent.setDrawingCacheEnabled(true);

            addViewContent.measure(
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

            addViewContent.layout(0, 0,
                    addViewContent.getMeasuredWidth(),
                    addViewContent.getMeasuredHeight());

            addViewContent.buildDrawingCache();
            Bitmap cacheBitmap = addViewContent.getDrawingCache();
            Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

            return bitmap;
        }
        return null;
    }


    /**
     * bitmap转为base64
     *
     * @param filePath
     * @return
     */
    public static String filePathToBase64(String filePath) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            Bitmap bitmap = BitmapFactory.decodeFile(filePath, null);
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String Bitmap2StrByBase64(Bitmap bit){
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.PNG, 100, bos);//参数100表示不压缩
        byte[] bytes=bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.NO_WRAP);
    }

}
